module disp_ctrl (
    input         sys_clk,
    input         rst_n,
    input         tbase_pulse_i,
    input         unit_sel_i,
    input  [11:0] bcdcnt_i,
    output [ 3:0] sel_o,
    output [ 7:0] seg_o
);

  reg  [3:0] cath_sel;
  reg  [1:0] n_cath;
  reg  [3:0] bcd_dig;
  wire       add_dot;

  always @(posedge sys_clk, negedge rst_n) begin
    if (~rst_n) begin
      n_cath <= 2'h0;
    end else if (tbase_pulse_i) begin
      if (n_cath == 2'h2) begin
        n_cath <= 2'h0;
      end else begin
        n_cath <= n_cath + 2'h1;
      end
    end
  end

  always @(*) begin
    case (n_cath)
      2'h0: cath_sel = 4'he;
      2'h1: cath_sel = 4'hd;
      2'h2: cath_sel = 4'hb;
      2'h3: cath_sel = 4'h7;
    endcase
  end

  // 单位为 Hz 时，点在末尾，单位为 kHz 时，点在第一位
  assign add_dot = (~unit_sel_i && (n_cath == 2'h2)) || (unit_sel_i && (n_cath == 2'h0));

  always @(*) begin
    case (n_cath)
      2'h0: bcd_dig = bcdcnt_i[11:8];
      2'h1: bcd_dig = bcdcnt_i[7:4];
      2'h2: bcd_dig = bcdcnt_i[3:0];
      default: bcd_dig = 4'hf;
    endcase
  end

  bcd2seg_cath bcd2seg_cath_inst (
      .bcdcode_i(bcd_dig),
      .dot_i(add_dot),
      .seg_o(seg_o)
  );
  assign sel_o = cath_sel;
endmodule

module bcd2seg_cath (
    input  [3:0] bcdcode_i,
    input        dot_i,
    output [7:0] seg_o
);

  // segment order: dp g f e d c b a
  reg [7:0] seg_s;
  always @(*) begin
    case (bcdcode_i)
      4'h0: seg_s = {dot_i, 7'h3f};
      4'h1: seg_s = {dot_i, 7'h06};
      4'h2: seg_s = {dot_i, 7'h5b};
      4'h3: seg_s = {dot_i, 7'h4f};
      4'h4: seg_s = {dot_i, 7'h66};
      4'h5: seg_s = {dot_i, 7'h6d};
      4'h6: seg_s = {dot_i, 7'h7d};
      4'h7: seg_s = {dot_i, 7'h07};
      4'h8: seg_s = {dot_i, 7'h7f};
      4'h9: seg_s = {dot_i, 7'h6f};
      default: seg_s = 8'h00;
    endcase
  end
  assign seg_o = seg_s;
endmodule
